from docx import Document
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.shared import Inches

#https://codeantenna.com/a/Q0W1v0c699
#https://www.zhihu.com/question/276501307

if __name__ == '__main__':
    print("开始执行")


    # doc = Document("D:\\hjx\\project\\python\\python-test\\testExcel\\imginsert.docx")
    doc = Document("C:\\Users\\11578\\Desktop\\test1.docx")

    # 添加表格
    # 添加一个2行2列的空表
    tab = doc.add_table(rows=2, cols=2)
    # 获取某单元格对象（从0开始索引）
    cell0 = tab.cell(0, 0)
    c_p0 = cell0.paragraphs[0]
    # 设置单元格内容居中对齐
    c_p0.paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
    c_run0 = c_p0.add_run()

    cell1 = tab.cell(0, 1)
    c_p1 = cell1.paragraphs[0]
    # 设置单元格内容居中对齐
    c_p1.paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
    c_run1 = c_p1.add_run()

    cell2 = tab.cell(1, 0)
    c_p2 = cell2.paragraphs[0]
    # 设置单元格内容居中对齐
    c_p2.paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
    c_run2 = c_p2.add_run()

    cell3 = tab.cell(1, 1)
    c_p3 = cell3.paragraphs[0]
    # 设置单元格内容居中对齐
    c_p3.paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
    c_run3 = c_p3.add_run()

    c_run0.add_picture("testExcel\\img.png", width=Inches(2.1),height=Inches(2.6))
    c_p0.add_run("图一")
    c_run1.add_picture("testExcel\\img.png", width=Inches(2.1),height=Inches(2.6))
    c_p1.add_run("图二")
    c_run2.add_picture("testExcel\\img.png", width=Inches(2.1),height=Inches(2.6))
    c_p2.add_run("图三")
    c_run3.add_picture("testExcel\\img.png", width=Inches(2.1),height=Inches(2.6))
    c_p3.add_run("图四")



    #保存doc文档
    doc.save('testExcel\\imginsertresult.docx')

    print("执行完成")